Skip to content

fix: make generation_stream thread-local (MLX #3348 compat) - #1088

Closed
Thump604 wants to merge 1 commit into
ml-explore:mainfrom
Thump604:fix/thread-local-generation-stream
Closed

Thump604 wants to merge 1 commit into
ml-explore:mainfrom
Thump604:fix/thread-local-generation-stream

Conversation

@Thump604

@Thump604 Thump604 commented Apr 1, 2026

Copy link
Copy Markdown

Summary

Make generation_stream thread-local to work with MLX's thread-local CommandEncoder (ml-explore/mlx#3348).

Problem

generation_stream = mx.new_stream(mx.default_device()) is created at module import on the main thread. When generation runs in a worker thread (e.g., vllm-mlx BatchedEngine uses asyncio.to_thread), MLX's thread-local CommandEncoder cannot find the stream:

RuntimeError: There is no Stream(gpu, 0) in current thread.

This breaks any server that dispatches generation to a thread pool, which is the standard pattern for async inference servers.

Fix

Replace the module-level mx.Stream with a threading.local()-backed factory function. Each thread creates its own stream on first use.

# Before (module-level, single thread only):
generation_stream = mx.new_stream(mx.default_device())

# After (per-thread):
def generation_stream() -> mx.Stream:
    s = getattr(_generation_stream_storage, "stream", None)
    if s is None:
        s = mx.new_stream(mx.default_device())
        _generation_stream_storage.stream = s
    return s

Call sites change from generation_stream to generation_stream(). 7 call sites updated.

Backward compatible: on MLX versions without thread-local command encoders, per-thread streams work identically.

Test plan

  • Verified with vllm-mlx BatchedEngine (thread pool dispatch) on MLX with #3348
  • No behavior change on pre-#3348 MLX
  • 1 file, 21 insertions, 9 deletions

MLX ml-explore/mlx#3348 (Make CommandEncoder thread local) makes each
thread maintain its own Metal command encoder. The module-level
generation_stream created at import time belongs to the main thread's
command encoder. When generation runs in a thread pool (e.g., via
vllm-mlx BatchedEngine), mx.eval and mx.synchronize on that stream
fail with:

    RuntimeError: There is no Stream(gpu, 0) in current thread.

Fix: replace the module-level mx.Stream with a thread-local factory
function. Each thread gets its own stream on first use. The public
name `generation_stream` becomes a function returning the current
thread's stream, keeping the call-site diff minimal.

Backward compatible: on MLX versions without thread-local command
encoders, per-thread streams work identically to a shared stream.
@angeloskath

Copy link
Copy Markdown
Member

Closing in favor of #1090 which does a more comprehensive fix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants